package com.roamer.school.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.roamer.school.common.exception.suppert.DataConflictException;
import com.roamer.school.common.util.Md5Utils;
import com.roamer.school.repository.entity.sys.SysUser;
import com.roamer.school.repository.enums.UserStatusEnum;
import com.roamer.school.repository.mapper.sys.UserMapper;
import com.roamer.school.service.model.sys.UserDTO;
import com.roamer.school.service.sys.UserService;
import com.roamer.school.shiro.util.CodecUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 用户逻辑层 实现
 *
 * @author roamer
 * @version V1.0
 * @date 2019/1/2 10:52
 */
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {

    @Override
    public SysUser findByUsername(String username) {
        return baseMapper.selectByUsername(username);
    }

    @Override
    public SysUser findEffectiveByUsername(String username) {
        Wrapper<SysUser> ew = new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, username);
        return baseMapper.selectOne(ew);
    }

    @Override
    public IPage<SysUser> findPage(Page<SysUser> page, UserDTO user) {
        return baseMapper.selectPageByMultiple(page, user.getUsername());
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public SysUser saveUser(UserDTO userDTO) {
        // 查询用户名是否已经存在
        SysUser sysUser = baseMapper.selectByUsername(userDTO.getUsername());
        if (Objects.nonNull(sysUser)) {
            throw new DataConflictException();
        }

        SysUser user = userDTO.reverseConvert();
        // 设置盐
        user.setSalt(Md5Utils.md5Encode(null, user.getUsername()));
        String password = CodecUtils.encipher(user.getPassword(), user.getCredentialsSalt());
        user.setPassword(password);
        // 默认用户为未激活状态
        user.setStatus(UserStatusEnum.DISABLE);
        baseMapper.insert(user);
        return user;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public SysUser updateUser(UserDTO userDTO) {
        SysUser user = userDTO.reverseConvert();
        baseMapper.updateById(user);
        return user;
    }

}
